class User < ActiveRecord::Base
  paginates_per 20

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable

  attr_accessible :email, :password, :password_confirmation, :remember_me,
                  :first_name, :last_name, :avatar

  has_many :documents,    :dependent => :nullify
  has_many :comments,     :dependent => :destroy
  has_and_belongs_to_many :roles
  has_and_belongs_to_many :conferences

  validates_presence_of :first_name, :last_name

  has_attached_file :avatar,
                    :styles => {:thumb => "32x32", :small => "64x64" },
                    :default_url => 'icons/anonymous_:style.png'

  validates_attachment_size :avatar,
                            :less_than => 100.kilobytes
  validates_attachment_content_type :avatar, :content_type => ['image/jpeg', 'image/png', 'image/gif']

  scope :feed, where(:admin => false)

  after_create :assign_roles, :unless => :administrator?

  def full_name
    "#{self.first_name} #{self.last_name}"
  end

  def avatar_url(size=:thumb)
    ActionController::Base.helpers.image_path self.avatar.url(size)
  end

  def administrator?
    self.admin?
  end

  def role?(role)
    !!self.roles.find_by_name(role.to_s) || administrator?
  end

  private
    def assign_roles
      self.roles = Role.where(:default => true)
    end
end
